<?php

namespace app\api\controller;

use app\admin\model\Goods as GoodsModel;
use app\admin\model\Explosive as Explosive;
use app\admin\model\Overbalance as Overbalance;
use app\admin\model\Recommend as Recommend;
use app\common\controller\Api;
use app\common\model\Authentication;
use EasyWeChat\Factory;
use think\Config;
use think\Env;
use think\Log;
use think\Validate;

/**
 * 商品接口
 */
class Goods extends Api
{
    protected $noNeedLogin = ['index','detail'];
    protected $noNeedRight = ['*'];
    public function _initialize(){
        parent::_initialize();

        $this->Goods = new GoodsModel;
        $this->Explosive = new Explosive;
        $this->Overbalance = new Overbalance;
        $this->Recommend = new Recommend;
    }

    /**
     * 类别
     */
    public function category()
    {
        $category = [
            '红壳洋鸡蛋','粉壳草鸡蛋','小码虫草蛋'
        ];
        $this->success('类别',[
            'category' => $category
        ]);
    }
    /**
     * 商品列表
     */
    public function index()
    {
        $goods = $this->Goods;
        $type = request()->param('type',0);//1爆品 2超值 3推荐
        switch ($type) {
            case 1://爆品
                $goods = $this->explosive($goods);
                break;
            case 2://超值
                $goods = $this->overbalance($goods);
                break;
            case 3://推荐
                $goods = $this->recommend($goods);
                break;
        }
        $keyword = request()->param('keyword');
        if($keyword){
            $goods = $goods->where('title','like',"%{$keyword}%");
        }
        $status = request()->param('status');
        if($status){
            $goods = $goods->where('status','=',$status);
        }
        $userid = $this->auth->id;
        $sell = request()->param('sell');
        $is_seller = request()->param('is_seller');//1卖出 2买入
        if($sell){
            $goods = $goods->where('user_id','=',$userid);
            if($is_seller){
                $goods = $goods->where('is_seller','=',$is_seller);
            }
        }else{
//            $goods = $goods->where('user_id','<>',$userid);
            if($is_seller == 1){
                $goods = $goods->where('is_seller','=',2);
            }elseif ($is_seller == 2){
                $goods = $goods->where('is_seller','=',1);
            }
        }

        $limit = request()->param('limit',20);
        $order = request()->param('order','createtime');
        $sort = request()->param('sort','desc');
        $order1 = request()->param('torder','createtime');
        $sort1 = request()->param('tsort','desc');
        // 定义排序字段和排序方式
        $orderBy = [
            $order => $sort,  // 按年龄降序排序
            $order1 => $sort1,  // 在年龄相同的情况下按姓名升序排序
        ];
        $goods = $goods->with(['order'])->order($orderBy)->paginate($limit);
        $this->success('请求成功',[
            'goods'=>$goods,
        ]);
    }

    /**
     * 详情
     */
    public function detail()
    {
        $user = $this->auth->getUser();
        $goods_id = request()->param('goods_id');
        if(!$goods_id){
            $this->error('参数不全');
        }
        $goods = $this->Goods
            ->with(['order'])
            ->withCount(['collect'=>function($qurey) use($user) {
                $qurey->where('user_id',$user->id);
            }])
            ->where('id','=',$goods_id)->find();
        $earnest = Config::get('site.earnest');
        $buyer_commission = Config::get('site.buyer_commission');
        $this->success('商品详情',[
            'earnest'=>$earnest,//买家定金比例
            'goods'=>$goods,
            'buyer_commission'=>$buyer_commission//买家抽成比例
        ]);
    }
    /**
     * 爆品
     */
    public function explosive($goods)
    {
        $explosive = db('explosive_goods')
            ->where('status','=',1)
            ->field('id,goods_id,user_id')
            ->select();
        $arr = [];
        if(!empty($explosive)){
            foreach ($explosive as $v){
                array_push($arr,$v['goods_id']);
            }
        }
        $goods = $goods->whereIn('id',$arr);
        return $goods;
    }
    /**
     * 超值
     */
    public function overbalance($goods)
    {
        $overbalance = db('overbalance_goods')
            ->where('status','=',1)
            ->field('id,goods_id,user_id')
            ->select();
        $arr = [];
        if(!empty($overbalance)){
            foreach ($overbalance as $v){
                array_push($arr,$v['goods_id']);
            }
        }
        $goods = $goods->whereIn('id',$arr);
        return $goods;
    }
    /**
     * 推荐
     */
    public function recommend($goods)
    {
        $recommend = db('recommend_goods')
            ->where('status','=',1)
            ->field('id,goods_id,user_id')
            ->select();
        $arr = [];
        if(!empty($recommend)){
            foreach ($recommend as $v){
                array_push($arr,$v['goods_id']);
            }
        }
        $goods = $goods->whereIn('id',$arr);
        return $goods;
    }

    /**
     * 发布商品
     */
    public function add()
    {
        $user = $this->auth->getUser();
        $data = request()->param();
        if(empty($data['title']) || empty($data['image']) || empty($data['price']) || empty($data['selltime']) || empty($data['real_name']) || empty($data['phone']) || empty($data['is_seller'])){
            $this->error('请检查信息填写是否完整');
        }
        $log = Authentication::where('user_id',$user['id'])->where('is_attestation',2)->find();
        if(!$log) $this->error('请先进行实名认证');
        if(empty($data['num']) || $data['num'] < 0) $this->error('请输入正确的数量');
        if($data['price'] <= 0) $this->error('请输入正确的金额');
        $max_nun = Config::get('site.max_nun');
        $min_num = Config::get('site.min_num');
        if($data['num'] > $max_nun || $data['num'] < $min_num){
            $this->error('超出限制数量');
        }
        //卖家保证金比例
        $margin = Config::get('site.sell_earnest');
        //卖家抽成比例
        $seller_commission = Config::get('site.seller_commission');
        if(isset($data['is_seller']) && $data['is_seller'] == 2){
            //买家保证金
            $margin = Config::get('site.earnest');
            $seller_commission = Config::get('site.buyer_commission');
        }
        //单价*数量*比例
        $money = bcmul(bcmul($data['num'],$data['price'],2),$margin,2);
        $data['earnest_money'] = $money;
        $data['seller_commission'] = $seller_commission;
        $total_money = $money;
        if (!Validate::regex($data['phone'], "^1\d{10}$")) {
            $this->error(__('请输入正确的手机号'));
        }
        if(isset($data['is_explosive']) && $data['is_explosive'] > 0){
            //爆品
            $explosive = Config::get('site.exposure_fee');
            $data['exposure_fee'] = $explosive;
            $total_money += $explosive;
        }
        if(isset($data['is_overbalance']) && $data['is_overbalance'] > 0){
            //超值
            $overbalance = Config::get('site.premium_fee');
            $data['premium_fee'] = $overbalance;
            $total_money += $overbalance;
        }
        if(isset($data['is_recommend']) && $data['is_recommend'] > 0){
            //今日推荐
            $recommend = Config::get('site.referral_fee');
            $data['referral_fee'] = $recommend;
            $total_money += $recommend;
        }
        //跳支付，支付保证金
        $result = $this->pay($user,$data,$total_money);
        if($result){
            $this->success('去支付',$result);
        }
        $this->error('支付暂未开通');
//        //TODO 测试
//        $trade_no = 'wx'.time().rand(1000,9999);
//        \db('paylog')->insert([
//            'user_id' => $user->id,
//            'goods' => json_encode($data),
//            'trade_no' => $trade_no,
//            'state' => 1,
//            'type' => 1,
//            'money' => $total_money,
//            'createtime' => time(),
//            'updatetime' => time()
//        ]);
//        $order = db('paylog')->where('trade_no',$trade_no)->find();
//        if (!$order || $order['state'] != 1) { // 如果订单不存在 或者 订单已经支付过了
//            $this->error('支付暂未开通');
//        }
//        db('paylog')->where('id',$order['id'])->update([
//            'pay_time' => date('Y-m-d H:i:s',time()),
//            'state' => 2
//        ]);
//        $this->Goods->add(json_decode($order['goods']),$order['user_id'],1111);
//        $this->success('添加成功');
    }
    /**
     * 微信支付
     */
    public function pay($user,$data,$total_money)
    {
        //$type 1购物车下单 2直接下单
        $config = $this->config();
        $app = Factory::payment($config);
        $trade_no = 'wx'.time().rand(1000,9999);
        $url = Env::get('app.app_url', 'https://admin.danmaimai.cn');
        $result = $app->order->unify([
            'body' => '微信支付',
            'out_trade_no' => $trade_no,
            'total_fee' => $total_money * 100,
            'spbill_create_ip' => '', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => $url.'/api/pay/notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $user->openid,
        ]);
        if ($result['return_code'] === 'SUCCESS' && $result['result_code'] === 'SUCCESS') {
            $result = $app->jssdk->sdkConfig($result['prepay_id']); //第二次签名
            $result['price'] = (string)($total_money * 100);
            $result['out_trade_no'] = (string)$trade_no;
            $result['date'] = (string)date('Y-m-d H:i:s');
            // 保存订单信息
            \db('paylog')->insert([
                'user_id' => $user->id,
                'goods' => json_encode($data),
                'trade_no' => $trade_no,
                'state' => 1,
                'type' => 1,
                'money' => $total_money,
                'createtime' => time(),
                'updatetime' => time()
            ]);
            $result["orderId"] = $trade_no;
            return $result;
        }
        return false;
    }

    /**
     * 配置
     * @return string[]
     */
    public function config()
    {
        //获取插件
        $config = get_addon_config('epay');
        $config = [
            // 必要配置
            'app_id'             => $config['wechat']['miniapp_id'],
            'mch_id'             => $config['wechat']['mch_id'],
            'key'                => $config['wechat']['key'],   // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)
            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path'          => ROOT_PATH.'addons/epay/certs/apiclient_cert.pem', // XXX: 绝对路径！！！！
            'key_path'           => ROOT_PATH.'addons/epay/certs/apiclient_key.pem',      // XXX: 绝对路径！！！！
            'notify_url'         => '',     // 你也可以在下单时单独设置来想覆盖它
        ];
        return $config;
    }

    /**
     * 编辑
     * @return void
     */
    public function edit()
    {
        $user = $this->auth->getUser();
        $data = request()->param();
        if(!$data['id']){
            $this->error('参数错误');
        }
        $id = $data['id'];
        $goods = $this->Goods->where('id',$data['id'])->find();
        if(!$goods){
            $this->error('商品不存在');
        }
        if($goods['status'] == 3){
            $this->error('该商品已售');
        }
//        if($data['images']){
//            $data['images'] = json_encode($data['images']);
//        }
        unset($data['id']);
        unset($data['exposure_fee']);
        unset($data['referral_fee']);
        unset($data['premium_fee']);
        unset($data['earnest_money']);
        $this->Goods->where('id',$id)->update($data);
        $this->success('成功');
    }

    /**
     * 删除
     * @return void
     */
    public function del()
    {
        $id = request()->param('goods_id');
        if(!$id){
            $this->error('参数错误');
        }
        $goods = $this->Goods->where('id',$id)->delete();
        if($goods){
            $this->Explosive->where('goods_id',$id)->delete();
            $this->Overbalance->where('goods_id',$id)->delete();
            $this->Recommend->where('goods_id',$id)->delete();
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }

    /**
     * 下架
     */
    public function updown()
    {
        $user = $this->auth->getUser();
        $id = request()->param('goods_id');
        $status = request()->param('status');
        if(!$id || !$status){
            $this->error('参数错误');
        }
        $goods = $this->Goods->where(['id'=>$id,'user_id'=>$user->id])->find();
        if($status == 1){
            $state = 1;
            if(!$goods || $goods['status'] != 2){
                $this->error('已下架商品才可以上架');
            }
        }else{
            $state = 2;
            if(!$goods || $goods['status'] != 1){
                $this->error('发布中商品才可以下架');
            }
        }
        $re = $this->Goods->where(['id'=>$id,'user_id'=>$user->id])->update([
            'status' => $state
        ]);
        db('explosive_goods')->where(['goods_id'=>$id])->update([
            'status' => $state
        ]);
        db('overbalance_goods')->where(['goods_id'=>$id])->update([
            'status' => $state
        ]);
        db('recommend_goods')->where(['goods_id'=>$id])->update([
            'status' => $state
        ]);
        if($re){
            $this->success('成功');
        }
        $this->error('失败');
    }
}
